package com.dongdongshop.controller;

import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(topic = "phone-topic",consumerGroup = "phone_message")
public class MessageController implements RocketMQListener<String> {

    @Autowired
    private RedisTemplate redisTemplate;


/*    @RequestMapping("sendMessage")
    @ResponseBody
    public String sendMessage(String phoneNum){
        //phoneNum手机号
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient("apikey").init();
        //发送短信API
        String Code = RandomStringUtils.randomNumeric(6);
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phoneNum);
        param.put(YunpianClient.TEXT, "【云片网】您的验证码是"+Code+"赶紧验证一会过期了,");
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
        //获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        //账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*
        //释放:clnt.close() 释放后clnt将无法再使用
        clnt.close();
        return"ok";
    }*/

    @Override
    public void onMessage(String phoneNum) {
        //初始化clnt,使用单例方式
        YunpianClient clnt = new YunpianClient("6b3ee03d0f730196184864e960e826db").init();
        Random random = new Random();
        String Code = RandomStringUtils.randomNumeric(6);
//发送短信API
        Map<String, String> param = clnt.newParam(2);
        param.put(YunpianClient.MOBILE, phoneNum);
        param.put(YunpianClient.TEXT, "【云片网】用户您好，您的验证码是"+Code+"。有效期为30分钟，请尽快验证");
        Result<SmsSingleSend> r = clnt.sms().single_send(param);
//获取返回结果，返回码:r.getCode(),返回码描述:r.getMsg(),API结果:r.getData(),其他说明:r.getDetail(),调用异常:r.getThrowable()
        if(r.getCode() ==  0){
            redisTemplate.opsForValue().set(phoneNum,Code,30, TimeUnit.MINUTES);
       }
//账户:clnt.user().* 签名:clnt.sign().* 模版:clnt.tpl().* 短信:clnt.sms().* 语音:clnt.voice().* 流量:clnt.flow().* 隐私通话:clnt.call().*

//释放:clnt.close() 释放后clnt将无法再使用
        clnt.close();
    }

    }

